// src/call-baidu.js

const url = require('url')
const { join } = require('path')

const axios = require('axios')
const fsx = require('fs-extra')

const { MD5 } = require('./md5')

const config = fsx.readJsonSync(join(__dirname, '..', 'app.json'))

/**
 * Basically we expect the first input point to a file
 * then --from (default en)
 * --to (default cn)
 *
 */
function callBaidu(q, from, to) {
  const { appid, key } = config
  const salt = (new Date()).getTime()
  const sign = MD5(appid + q + salt + key)
  const params = new url.URLSearchParams(
    {
      q,
      appid,
      salt,
      from,
      to,
      sign
    }
  )

  return axios.post(
    'http://api.fanyi.baidu.com/api/trans/vip/translate',
    params.toString(),
    {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    }
  )
  .then(res => res.data)
}

module.exports = { callBaidu }
